<?php

namespace app\common\model;

use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'image_str',
        'images_array',
    ];



    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public static function getCartNum($goods_id, $user_id)
    {
        return Cart::where('goods_id', $goods_id)->where('user_id', $user_id)->value('num') ?? 0;
    }

    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function getImageStrAttr($value, $data)
    {
        return $data['image'] ? cdnurl($data['image'], true) : '';
    }
    public function getImagesArrayAttr($value, $data)
    {
        $arr = explode(',', $data['images']);
        foreach ($arr as &$v) {
            $v = cdnurl($v, true);
        }
        return $arr;
    }
    /**
     * 读取商品列表
     * @param int $cate_id   指定类型
     * @param string $keywords 指定状态
     * @return array
     */
    public static function getGoodsList(int $cate_id, $keywords = null)
    {

        $list = self::where(function ($query) use ($cate_id, $keywords) {
            if (!is_null($cate_id) && $cate_id) {
                $query->where('category_id', '=', $cate_id);
            }
            if (!is_null($keywords)) {
                $query->whereLike('title', '%' . $keywords . '%');
            }
            $query->where('status', 'normal');
        })->paginate();
        return $list;
    }
}
